package com.mark.controller.backend;

import com.google.common.collect.Maps;
import com.mark.common.ServerResponse;
import com.mark.controller.common.CurrentUser;
import com.mark.enums.PropertiesEnum;
import com.mark.pojo.Product;
import com.mark.pojo.User;
import com.mark.service.IFileService;
import com.mark.service.IProductService;
import com.mark.util.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Created by Mark on 2018/3/26.
 * 商品被【后台管理】 和 【卖家】 调用的接口
 */

@Controller
@RequestMapping("/manage/product/")
public class ProductManageController {
    @Autowired
    private IProductService iProductService;
    @Autowired
    private IFileService iFileService;


    //1.保存商品（添加，更新）
    @RequestMapping(value="save_product.do" , method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse productSave(HttpSession session, Product product,HttpServletRequest httpServletRequest){
        ServerResponse response = CurrentUser.getCurrentUser(httpServletRequest);
        if (!response.isSuccess()){
            product.setOwnerId(0);
        }else{
            User currentUser = (User) response.getData();
            product.setOwnerId(currentUser.getId());
        }
        return iProductService.insertOrUpdateProduct(product);
    }

    //2.修改产品销售状态
    @RequestMapping(value="set_sale_status.do" , method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse setSaleStatus(Integer productId,Integer status){
        return  iProductService.setSaleStatus(productId,status);
    }

    //3.获取商品详情
    //admin
    @RequestMapping(value="product_detail.do" , method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse productDetail(Integer productId){
        return iProductService.getProductDetail(productId);
    }

    //4.商品按创建时间升序分页显示
    //4.1：后台调用（ownerId 不用传值）
    @RequestMapping(value="product_list.do" , method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse getList(Integer ownerId,
                                  @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                                  @RequestParam(value = "pageSize",defaultValue = "10") int pageSize) {
        return iProductService.getProductList(pageNum,pageSize,ownerId);
    }

    //5.商品搜索：（1：按商品名模糊搜索）（2：按Id搜索）（3：按状态搜索）
    @RequestMapping(value="search_product.do" , method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse searchProduct(String productName,
                                        Integer productId,
                                        Integer status,
                                        @RequestParam(value = "pageNum",defaultValue ="1" ) int pageNum,
                                        @RequestParam(value = "pageSize",defaultValue ="10" )int pageSize){
        return iProductService.searchProduct(null,productName,productId,status,pageNum,pageSize);
    }

    //6.上传主图
    @RequestMapping(value="upload" , method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse upload(@RequestParam(value = "upload_file",required = false)MultipartFile file, HttpServletRequest request){
        String path = request.getSession().getServletContext().getRealPath("upload");
        String targetFileName = iFileService.upload(file,path,"",1);
        String url = PropertiesUtil.getProperty(PropertiesEnum.FTP_SERVICE_HTTP_PREFIX.getPropertiesName())+targetFileName;
        Map<String,Object> fileMap = Maps.newHashMap();
        fileMap.put("uri",targetFileName);
        fileMap.put("url",url);
        return ServerResponse.createBySuccess(fileMap);
    }

    //7.上传富文本图片
    @RequestMapping(value="richtext_img_upload" , method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> richtextImgUpload( @RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultMap = Maps.newHashMap();
        String path = request.getSession().getServletContext().getRealPath("upload");
        String targetFileName = iFileService.upload(file, path,"product",0);
        if (StringUtils.isBlank(targetFileName)) {
            resultMap.put("success", false);
            resultMap.put("msg", "上传失败");
            return resultMap;
        }
        String url = PropertiesUtil.getProperty(PropertiesEnum.FTP_SERVICE_HTTP_PREFIX.getPropertiesName()) + targetFileName;
        resultMap.put("success", true);
        resultMap.put("msg", "上传成功");
        resultMap.put("file_path", url);
        response.addHeader("Access-Control-Allow-Headers", "X-File-Name");
        return resultMap;
    }
}
